<template>
  <view>
    <view class="search-box">
      <uni-search-bar @input="input" :radius="100" cancelButton="none" v-model="kw" clearable></uni-search-bar>
    </view>
    <!-- 搜索建议列表 -->
    <view class="sugg-list" v-if="searchResults.length !== 0">
      <view class="sugg-item" v-for="(item,i) in searchResults" :key="i" @click="gotoDetail(item)">
        <view class="sugg-name">{{item.content}}</view>
        <uni-icons type="arrowright" size="16"></uni-icons>
      </view>
    </view>
    <!-- 搜索历史区域 -->
    <view class="history-box" v-else>
      <!-- 标题区域 -->
      <view class="history-title">
        <text>搜索历史</text>
        <uni-icons type="trash" size="20" @click="clean"></uni-icons>
      </view>
      <!-- 列表区域 -->
      <view class="history-list">
        <uni-tag :text="item" v-for="(item, i) in histories" :key="i" @click="gotoHistory(item)"></uni-tag>
      </view>
    </view>
  </view>
</template>

<script>
  export default {
    data() {
      return {
        timer: null,
        kw: '',
        //搜索的结果列表
        searchResults: [],
        //搜索历史的数组
        historyList: [],
        staticData: []
      };
    },
    onLoad() {
      
      //JSON.parse用于将 JSON 字符串 转换为对应的 JavaScript 对象或值
      this.historyList = JSON.parse(uni.getStorageSync('kw') || '[]')
    },
    methods: {
      //input 输入事件的处理函数, 输入防抖
      input(e) {
        clearTimeout(this.timer)
        this.timer = setTimeout(() => {
          // console.log(e)
          this.kw = e
          this.getSearchList()
        },500)
      },
      getSearchList() {
        // 判断搜索关键词是否为空
        if (this.kw.length === 0) {
          this.searchResults = []
          return
        }
        
        uniCloud.callFunction({
          name: "Cloudzhusu",
          data: {}
        }).then(res => {
          console.log(res)
          this.staticData = res.result.data
          
          // 筛选时同时匹配 title 和 content，并保留所属的 category
          const filtered = this.staticData.flatMap(item => {
            const results = []
            
            // 1. 检查 title 是否包含关键词
            if (item.title.includes(this.kw)) {
              results.push({
                category: item.category,
                title: item.title,
                content: item.title, // 如果是标题匹配，content 也显示标题
                matchType: 'title'   // 标记匹配类型
              })
            }
            
            // 2. 检查 content 数组中的每一项是否包含关键词
            item.content.forEach(contentItem => {
              if (contentItem.includes(this.kw)) {
                results.push({
                  category: item.category,
                  title: item.title,
                  content: contentItem,
                  matchType: 'content' // 标记匹配类型
                })
              }
            })
            
            return results
          })
          
          this.searchResults = filtered
          this.saveSearchHistory()
        })
      },
      
      
      gotoDetail(item) {
        console.log(item.title)
        if(item.category ==='租房') {
          uni.navigateTo({
          url: '/pages/zhusu/zhusu?activeIndex=0'
          })
        }
        if(item.category === '买房'){
          uni.navigateTo({
          url: '/pages/zhusu/zhusu?activeIndex=1'
          })
        }
        if(item.category === '住房装修'){
          uni.navigateTo({
          url: '/pages/zhusu/zhusu?activeIndex=2'
          })
        }
        
      },
      //本地持久化存储
      saveSearchHistory() {
        // this.historyList.push(this.kw)
      
        //Set对象是值的集合，Set中元素的值是唯一的
        const set = new Set(this.historyList)
        set.delete(this.kw)
        set.add(this.kw)
        //将set转换为Array数组
        this.historyList = Array.from(set)
        //setStorageSync对搜索历史数据持久化存储到本地
        //JSON.stringify用于将historyList转换成字符串，键为kw
        uni.setStorageSync('kw',JSON.stringify(this.historyList))
      },
      
      clean() {
        this.historyList = []
        uni.setStorageSync('kw', '[]')
      },
      gotoHistory(item) {
        // 1. 将历史文本填入搜索框
        this.kw = item;
        // 2. 触发搜索推荐（直接调用搜索逻辑，无需等待输入防抖）
        this.getSearchList();
        // 3. （可选）刷新历史记录（将当前点击的历史置顶）
        this.saveSearchHistory();
      }
    },
    //反转历史数据
    computed: {
      histories() {
        return [...this.historyList].reverse()
      }
    }
  }
</script>

<style lang="scss">
  .search-box {
    position: sticky;
    top: 0;
    z-index: 999;
  }
  .sugg-list {
    padding: 0 5px;
    .sugg-item{
      display: flex;
      align-items: center;
      justify-content: space-between;
      font-size: 15px;
      padding: 13px 0;
      border-bottom: 1px solid #efefef;
      .sugg-name{
        //文本不允许换行（单行文本）
        white-space: nowrap;
        //溢出部分隐藏
        overflow: hidden;
        //文本溢出后，使用...代替
        text-overflow: ellipsis;
      }
    }
  }
  .history-box {
    padding: 0 5px;
    .history-title {
     display: flex;
     justify-content: space-between;
     height: 46px;
     align-items: center;
     font-size: 16px;
     border-bottom: 1px solid #efefef;
    }
    .history-list {
      display: flex;
      flex-wrap: wrap;
      .uni-tag {
        margin-top: 5px;
        margin-right: 5px;
      }
    }
  }

</style>
